package com.hqj.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

@Controller
@RequestMapping("/cc")
public class ConsumerController {

    private String server_name = "http://hystrix-provider-8001:8001/";

    @Autowired
    private RestTemplate restTemplate; //fegin

    @RequestMapping("/showInfo")
    @ResponseBody
    public String showInfo(){
        return restTemplate.getForObject(server_name+"getInfo",String.class);
    }

    /**
     * 简单的熔断异常处理
     */
    @RequestMapping("/showInfo2")
    @ResponseBody
    @HystrixCommand(fallbackMethod = "getHystrixInfo")  //异常时发生熔断处理
    public String showInfo2(){
        String value = "";
        if("".equals(value)){
            throw new RuntimeException("抛出异常");
        }
        return restTemplate.getForObject(server_name+"getInfo",String.class);
    }

    /**
     *复杂的熔断处理，超过请求时间
     */
    @RequestMapping("/showInfo3")
    @ResponseBody
    @HystrixCommand(
            fallbackMethod = "getHystrixInfo",
            commandProperties = {
                    //降级处理超时时间设置
                    @HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value = "3000"),
                    //任意时间点允许的最高并发数。超过该设置值的，拒绝执行请求
                    @HystrixProperty(name="fallback.isolation.semaphore.maxConcurrentRequests",value = "1000")
            },
            //配置执行的线程池
            threadPoolProperties = {
                    @HystrixProperty(name="coreSize",value = "20"),
                    @HystrixProperty(name = "maxQueueSize",value="-1")
            },
            //排除不产生熔断的异常
            ignoreExceptions = {RuntimeException.class}
    )
    public String showInfo3(@RequestParam("time") int time){
        String value = "123";
        if("".equals(value)){
            throw new RuntimeException("抛出异常");
        }
        return restTemplate.getForObject(server_name+"getInfo2?time="+time,String.class);
    }

    public String getHystrixInfo(){
        return "服务被熔断";
    }

    public String getHystrixInfo(int time){
        return "服务被熔断,访问超时，时间："+time;
    }
}
